package hr.web.jsf.converters;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

@Name("mapConverter")
@BypassInterceptors
@org.jboss.seam.annotations.faces.Converter
public class MapConverter implements Converter {

	public static Object getAsObject(final String parameters) {
		if (parameters == null) {
			return null;
		}
		final Map<String, String> p = new HashMap<String, String>();
		final Scanner st = new Scanner(parameters).useDelimiter(";");

		while (st.hasNext()) {
			final StringTokenizer st2 = new StringTokenizer(st.next(), "=");
			final String name = st2.nextToken();
			final String value = st2.hasMoreTokens() ? st2.nextToken() : null;
			if (!name.equals("null")) {
				p.put(name, value);
			}
		}
		return p;
	}

	@SuppressWarnings("unchecked")
	public static String getAsString(final Map parameters) {
		String p = "";
		final Set<String> keys = parameters.keySet();
		int count = 0;
		for (final String key : keys) {
			if (!key.equals("null") && parameters.get(key) != null
					&& !parameters.get(key).equals("")) {
				if (count > 0) {
					p += ";";
				}
				p += key
						+ "="
						+ (parameters.get(key) == null
								|| parameters.get(key).equals("null") ? ""
								: parameters.get(key));
				count++;
			}
		}
		return p;
	}

	@Override
	public Object getAsObject(final FacesContext arg0, final UIComponent arg1,
			final String arg2) {
		return getAsObject(arg2);
	}

	@SuppressWarnings("unchecked")
	@Override
	public String getAsString(final FacesContext arg0, final UIComponent arg1,
			final Object arg2) {
		return getAsString((Map) arg2);
	}

}
